<template>
  <view class="goods-detail-page">
    <!-- 状态栏占位 -->
    <view class="status-bar"></view>
    
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <image class="back-icon" src="/static/Images/goods/Fanhui.png" mode="aspectFit"></image>
      </view>
      <view class="nav-search-container" @click="goSearch">
        <view class="nav-search-box">
          <image class="search-icon" src="/static/Images/goods/Sousu.png" mode="aspectFit"></image>
          <text class="search-placeholder">搜索商品</text>
        </view>
      </view>
      <view class="nav-more" @click="showMore">
        <image class="more-icon" src="/static/Images/goods/Gengduo.png" mode="aspectFit"></image>
      </view>
    </view>
    
    <!-- 商品主图和信息左右布局 -->
    <view class="goods-main-section">
      <!-- 左侧商品主图 -->
       <view class="goods-image-section">
         <image class="goods-image" :src="currentGoodsInfo.image || ''" mode="aspectFill"></image>
       </view>
      
      <!-- 右侧商品信息 -->
      <view class="goods-info-section">
        <view class="goods-title-section">
          <text class="goods-title">{{ currentGoodsInfo.title || '商品名称' }}</text>
        </view>
        <view class="price-section">
          <view class="price-container">
            <text class="price-symbol">¥</text>
            <text class="price-number">{{ selectedSpec ? selectedSpec.price : (currentGoodsInfo.price || '0.00') }}</text>
          </view>
          <text class="stock-info">库存：{{ selectedSpec ? selectedSpec.num : (currentGoodsInfo.stock || 0) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 商品类型选择 -->
    <!-- <view class="product-type-section">
      <text class="section-title">商品类型</text>
      <view class="option-buttons">
        <view class="option-btn" :class="{ active: selectedType === 'mobile' }" @click="selectType('mobile')">
          <text class="option-text">芒果手机端</text>
        </view>
        <view class="option-btn" :class="{ active: selectedType === 'tv' }" @click="selectType('tv')">
          <text class="option-text">芒果电视端</text>
        </view>
      </view>
    </view> -->
    
    <!-- 商品时长选择 -->
    <view class="product-duration-section" v-if="currentGoodsInfo.specs && currentGoodsInfo.specs.length > 0">
      <text class="section-title">商品规格</text>
      <view class="option-buttons">
        <view 
          class="option-btn" 
          :class="{ active: selectedSpec && selectedSpec.id === spec.id }" 
          @click="selectSpec(spec)"
          v-for="spec in currentGoodsInfo.specs" 
          :key="spec.id"
        >
          <text class="option-text">{{ spec.name }}</text>
        </view>
      </view>
    </view>

    <!-- 卡密有效期选择 -->
    <view class="quality-time-section">
      <!-- 保质时间选择 -->
      <view class="quality-time-container">
        <text class="section-label">保质时间</text>
        <view class="time-options">
          <view 
            v-for="(option, index) in qualityTimeOptions" 
            :key="index"
            class="time-option"
            :class="{ 'selected': option.selected }"
            @click="selectQualityTime(index)"
          >
            <view class="option-circle" :class="{ 'checked': option.selected }">
              <view v-if="option.selected" class="check-mark">✓</view>
            </view>
            <text class="option-label">{{ option.label }}</text>
          </view>
        </view>
      </view>
      
      <!-- 寄售类型选择 -->
      <!-- <view class="consignment-type-container">
        <view class="consignment-options">
          <view 
            class="consignment-option"
            :class="{ 'selected': consignmentType === 'single' }"
            @click="selectConsignmentType('single')"
          >
            <view class="option-circle" :class="{ 'checked': consignmentType === 'single' }">
              <view v-if="consignmentType === 'single'" class="check-mark">✓</view>
            </view>
            <text class="option-label">单个寄售</text>
          </view>
          
          <view 
            class="consignment-option selected"
            :class="{ 'selected': consignmentType === 'multiple' }"
            @click="selectConsignmentType('multiple')"
          >
            <view class="option-circle checked" :class="{ 'checked': consignmentType === 'multiple' }">
              <view v-if="consignmentType === 'multiple'" class="check-mark">✓</view>
            </view>
            <text class="option-label">多个寄售</text>
          </view>
        </view>
      </view> -->
    </view>
    
    <!-- 充值账号填写 -->
    <view class="account-section">
      <!-- 充值账号三列布局容器 -->
      <view class="account-header-container">
        <text class="section-title">卡密寄售</text>
        <view class="account-type-btn" :class="{ active: accountType === 'single' }" @click="selectAccountType('single')">
          <view class="radio-icon" :class="{ active: accountType === 'single' }"></view>
          <text class="account-type-text">单卡密类型</text>
        </view>
        <view class="account-type-btn" :class="{ active: accountType === 'multiple' }" @click="selectAccountType('multiple')">
          <view class="radio-icon" :class="{ active: accountType === 'multiple' }"></view>
          <text class="account-type-text">卡号卡密类型</text>
        </view>
      </view>
      
      <!-- 输入框和添加按钮两列布局容器 -->
      <view class="account-input-container">
        <view class="input-wrapper">
          <textarea 
            class="account-input" 
            placeholder="卡号和卡密之间使用“|”间隔，卡密之间请用换行符（回车）间隔，例如：
123456|123456
123456|123456
没有卡号的直接输入卡密，例如：
123456
123456" 
            v-model="accountNumber" 
            :auto-height="true"
            :maxlength="-1"
            :show-confirm-bar="false"
          ></textarea>
          <!-- <image class="add-icon-img floating-icon" v-if="accountType === 'multiple'" @click="addAccount" src="/static/Images/goods/Tianjia.png" mode="aspectFit"></image> -->
        </view>
      </view>
      

    </view>
    
    <!-- 卡密激活地址 -->
    <view class="activation-address-section">
      <text class="section-title">卡密激活地址</text>
      <view class="address-display">
        <text class="address-text">{{ currentGoodsInfo.charge_address || '暂无激活地址信息' }}</text>
      </view>
      
      <!-- 重要提示 -->
      <view class="warning-notice">
        <view class="notice-header">
          <image class="warning-icon" src="/static/Images/common/Xiaoxitongzhi.png" mode="aspectFit"></image>
          <text class="notice-title">重要提示</text>
        </view>
        <text class="notice-content">上架卡密必须是上述激活地址的渠道卡密，且能在上述地址激活使用，如果用户下单后不能通过该地址激活使用导致投诉的情况，会影响您的账号信誉评级，频繁投诉的账号还会有被封禁的风险！请核对您的卡密激活渠道地址再上架！</text>
      </view>
    </view>
    
    
    <!-- 购买数量 -->
    <!-- <view class="quantity-section">
      <text class="section-title">购买数量</text>
      <view class="quantity-control">
        <view class="quantity-btn" @click="decreaseQuantity">
          <text class="quantity-btn-text">-</text>
        </view>
        <text class="quantity-btn-text">|</text>
        <text class="quantity-value">{{ quantity }}</text>
        <text class="quantity-btn-text">|</text>
        <view class="quantity-btn" @click="increaseQuantity">
        
          <text class="quantity-btn-text">+</text>
        </view>
      </view>
    </view> -->
    
    <!-- 成交记录 -->
    <view class="transaction-section">
      <text class="section-title">成交记录</text>
      <view class="transaction-table">
        <!-- 表头 -->
        <view class="table-header">
          <text class="header-cell time-cell">成交时间</text>
          <text class="header-cell price-cell">价格</text>
          <text class="header-cell duration-cell">耗时</text>
        </view>
        <!-- 表格内容 -->
        <view class="table-body">
          <view class="table-row" v-for="(record, index) in transactionRecords" :key="index" :class="{ 'even-row': index % 2 === 1 }">
            <text class="body-cell time-cell">{{ record.time }}</text>
            <text class="body-cell price-cell">{{ record.price }}</text>
            <text class="body-cell duration-cell">{{ record.duration }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 销售渠道 -->
    <view class="channel-section">
      <text class="section-title">充值渠道</text>
      
      <!-- 支持的平台 -->
      <view class="platform-grid">
        <view 
          class="platform-item" 
          :class="{ supported: currentGoodsInfo.channel_ids.includes(platform.id), unsupported: !currentGoodsInfo.channel_ids.includes(platform.id) }"
          v-for="platform in platformList" 
          :key="platform.id"
        >
          <image 
             class="platform-icon" 
             :src="currentGoodsInfo.channel_ids.includes(platform.id) ? '/static/Images/goods/Zhichi.png' : '/static/Images/goods/Buzhichi.png'" 
             mode="aspectFit"
           ></image>
          <text class="platform-text">{{ platform.name }}</text>
        </view>
      </view>
    </view>
    
    <!-- 保障服务 -->
    <view class="guarantee-service-section">
      <view class="guarantee-section">
        <view class="guarantee-item">
          <image class="guarantee-icon" src="/static/Images/goods/Zhengpin.png" mode="aspectFit"></image>
          <text class="guarantee-text">正品保障</text>
        </view>
        <view class="guarantee-item">
          <image class="guarantee-icon" src="/static/Images/goods/Anquan.png" mode="aspectFit"></image>
          <text class="guarantee-text">安全保障</text>
        </view>
        <view class="guarantee-item">
          <image class="guarantee-icon" src="/static/Images/goods/Jisu.png" mode="aspectFit"></image>
          <text class="guarantee-text">极速到账</text>
        </view>
        <view class="guarantee-item">
          <image class="guarantee-icon" src="/static/Images/goods/Shouhou.png" mode="aspectFit"></image>
          <text class="guarantee-text">售后服务</text>
        </view>
      </view>
    </view>
    
    <!-- 商品详情 -->
    <view class="product-detail-section">
      <text class="section-title">商品详情</text>
      <view class="detail-content" v-html="safeHtml(currentGoodsInfo.content || '')">
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="bottom-left">
        <view class="bottom-btn" @click="goHome">
          <image class="home-icon" src="/static/Images/goods/Shouye.png" mode="aspectFit"></image>
          <text class="bottom-btn-text">首页</text>
        </view>
        <view class="bottom-btn" @click="contactService">
          <image class="service-icon" src="/static/Images/goods/Kefu.png" mode="aspectFit"></image>
          <text class="bottom-btn-text">客服</text>
        </view>
        <view class="bottom-btn" @click="contactService">
          <image class="service-icon" src="/static/Images/goods/Dingdan.png" mode="aspectFit"></image>
          <text class="bottom-btn-text">订单</text>
        </view>
      </view>
      <view class="bottom-right">
        <view class="buy-btn" @click="buyNow">
          <text class="buy-btn-text">立即寄售</text>
        </view>
      </view>
    </view>
    
    <!-- 立即购买弹窗 -->
    <GoodsBuy 
      :visible="showBuyModal" 
      :goodsInfo="currentGoodsInfo"
      :accountNumber="accountNumber"
      :orderId="currentOrderId"
      @close="closeBuyModal"
      @pay="handlePaymentComplete"
    />
    
    <!-- 价格设置弹窗 -->
    <PriceModal 
      :visible="showPriceModal"
      :defaultPrice="currentGoodsInfo.price"
      :quickPrices="getQuickPrices()"
      @close="closePriceModal"
      @confirm="confirmPrice"
    />
  </view>
</template>

<script>
import GoodsBuy from '@/components/Goodsbuy.vue'
import PriceModal from '@/components/PriceModal.vue'

export default {
  components: {
    GoodsBuy,
    PriceModal
  },
  data() {
    return {
      quantity: 1,
      selectedType: 'mobile',
      selectedDuration: '7days',
      accountType: 'single',
      accountNumber: '',
      accountList: [], // 多账号列表
      showBuyModal: false,
      showPriceModal: false, // 控制价格设置弹窗显示
      pendingCarmineList: [], // 待上架的卡密列表
      goodsId: null,
      loading: false,
      currentOrderId: '', // 保存当前创建的订单ID
      currentGoodsInfo: {
        title: '【账号充值】芒果TV会员7天',
        price: '18.92',
        stock: '999998',
        image: '',
        content: '',
        specs: [], // 商品规格数组
        channel_ids: [], // 支持的平台ID数组
        charge_address: '' // 卡密激活地址
      },
      platformList: [
        { id: 1, name: '咸鱼' },
        { id: 2, name: '得物' },
        { id: 3, name: '小红书' },
        { id: 4, name: '拼多多' },
        { id: 5, name: '淘宝' },
        { id: 6, name: '京东' },
        { id: 7, name: '抖音' },
        { id: 8, name: '限购' },
        { id: 9, name: 'API充值' }
      ],
      selectedSpec: null, // 当前选中的规格
      // 卡密有效期相关数据
      qualityTimeOptions: [
        { value: 3, label: '3天', selected: false },
        { value: 7, label: '7天', selected: true },
        { value: 15, label: '15天', selected: false },
        { value: 30, label: '30天', selected: false }
      ],
      consignmentType: 'multiple', // 寄售类型：single-单个寄售，multiple-多个寄售
      transactionRecords: [
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' }
      ]
    }
  },
  onLoad(options) {
    const id = options?.id || options?.goodsId || options?.goods_id || '';
    if (!id) {
      uni.showToast({ title: '未获取到商品ID', icon: 'none' });
      return;
    }
    this.goodsId = id;
    this.fetchGoodsInfo();
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 跳转搜索页面
    goSearch() {
      uni.navigateTo({
        url: '/pages/search'
      })
    },
    
    // 分享商品
    shareGoods() {
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 0,
        href: 'https://example.com',
        title: '商品分享',
        summary: '快来看看这个商品',
        imageUrl: 'https://via.placeholder.com/200x200'
      })
    },
    
    // 更多操作
    showMore() {
      uni.showActionSheet({
        itemList: ['收藏商品', '举报商品'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.showToast({
              title: '收藏成功',
              icon: 'success'
            })
          }
        }
      })
    },
    
    // 选择商品类型
    selectType(type) {
      this.selectedType = type
    },
    
    // 选择商品时长
    selectDuration(duration) {
      this.selectedDuration = duration
    },
    
    // 选择商品规格
    selectSpec(spec) {
      this.selectedSpec = spec;
      // 更新价格和库存
      this.currentGoodsInfo.price = spec.price || this.currentGoodsInfo.price;
      this.currentGoodsInfo.stock = spec.num || this.currentGoodsInfo.stock;
    },
    
    // 选择保质时间
    selectQualityTime(index) {
      // 取消所有选项的选中状态
      this.qualityTimeOptions.forEach(option => {
        option.selected = false;
      });
      // 设置当前选项为选中状态
      this.qualityTimeOptions[index].selected = true;
    },
    
    // 选择寄售类型
    selectConsignmentType(type) {
      this.consignmentType = type;
    },
    
    // 选择账号类型
    selectAccountType(type) {
      this.accountType = type;
      
      // 切换到单账号模式时，如果有多个账号，取第一个作为默认值
      if (type === 'single' && this.accountList.length > 0) {
        this.accountNumber = this.accountList[0];
        this.accountList = [];
      }
      
      // 切换到多账号模式时，如果有单个账号，添加到列表中
      if (type === 'multiple' && this.accountNumber.trim()) {
        if (!this.accountList.includes(this.accountNumber.trim())) {
          this.accountList.push(this.accountNumber.trim());
        }
        this.accountNumber = '';
      }
    },
    
    // 添加账号
    addAccount() {
      if (!this.accountNumber || !this.accountNumber.trim()) {
        uni.showToast({
          title: '请输入卡密',
          icon: 'none'
        });
        return;
      }
      
      // 按换行符分割多个卡密
      const accounts = this.accountNumber.trim().split('\n').filter(account => account.trim());
      
      if (accounts.length === 0) {
        uni.showToast({
          title: '请输入有效的卡密',
          icon: 'none'
        });
        return;
      }
      
      let addedCount = 0;
      let duplicateCount = 0;
      
      accounts.forEach(account => {
        const trimmedAccount = account.trim();
        if (trimmedAccount && !this.accountList.includes(trimmedAccount)) {
          this.accountList.push(trimmedAccount);
          addedCount++;
        } else if (this.accountList.includes(trimmedAccount)) {
          duplicateCount++;
        }
      });
      
      this.accountNumber = ''; // 清空输入框
      
      if (addedCount > 0) {
        uni.showToast({
          title: `成功添加${addedCount}个卡密${duplicateCount > 0 ? `，${duplicateCount}个重复` : ''}`,
          icon: 'success'
        });
      } else if (duplicateCount > 0) {
        uni.showToast({
          title: '所有卡密都已存在',
          icon: 'none'
        });
      }
    },
    
    // 移除账号
    removeAccount(index) {
      this.accountList.splice(index, 1);
      uni.showToast({
        title: '卡密已移除',
        icon: 'success'
      });
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    
    // 增加数量
    increaseQuantity() {
      this.quantity++
    },
    
    // 回到首页
    goHome() {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    },
    
    // 联系客服
    contactService() {
      uni.showToast({
        title: '客服功能待开发',
        icon: 'none'
      })
    },
    
    // 加入购物车
    addToCart() {
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      })
    },
    
    // 立即寄售
    async buyNow() {
      // 验证必填信息
      let carmineList = [];
      if (this.accountType === 'single') {
        if (!this.accountNumber || !this.accountNumber.trim()) {
          uni.showToast({
            title: '请输入卡密',
            icon: 'none'
          });
          return;
        }
        // 按换行符分割多个卡密
        const accounts = this.accountNumber.trim().split('\n').filter(account => account.trim());
        carmineList.push(...accounts);
      } else {
        // 多账号模式
        carmineList = [...this.accountList];
        
        // 如果输入框中有内容，也添加到卡密列表中
        if (this.accountNumber && this.accountNumber.trim()) {
          // 按换行符分割多个卡密
          const inputAccounts = this.accountNumber.trim().split('\n').filter(account => account.trim());
          inputAccounts.forEach(account => {
            const trimmedAccount = account.trim();
            // 检查是否已存在，避免重复
            if (trimmedAccount && !carmineList.includes(trimmedAccount)) {
              carmineList.push(trimmedAccount);
            }
          });
        }
        
        // 检查是否至少有一个卡密
        if (carmineList.length === 0) {
          uni.showToast({
            title: '请至少添加一个卡密',
            icon: 'none'
          });
          return;
        }
      }

      // 保存卡密列表，等待用户设置售价
      this.pendingCarmineList = carmineList;
      
      // 显示价格设置弹窗
      this.showPriceModal = true;
    },

    // 添加并上架卡密
    async addGoodsToMarket(carmineList, price) {
      try {
        uni.showLoading({ title: '正在上架卡密...' });
        
        // 获取选中的保质时间
        const selectedQualityTime = this.qualityTimeOptions.find(option => option.selected);
        const qualityDays = selectedQualityTime ? selectedQualityTime.value : 7;
        
        // 计算到期时间戳（当前时间 + 保质天数）
        const expireTime = Math.floor(Date.now() / 1000) + (qualityDays * 24 * 60 * 60);
        
        // 构造carmines数组
        const carmines = carmineList.map(carmineStr => {
          let carmine = carmineStr;
          let card_no = '';
          
          // 如果卡密中包含|，则拆分卡号和卡密
          if (carmineStr.includes('|')) {
            const parts = carmineStr.split('|');
            card_no = parts[0] || '';
            carmine = parts[1] || '';
          }
          
          return {
            carmine: carmine,
            price: price,
            time: expireTime,
            specs_value_ids: this.selectedSpec ? this.selectedSpec.id : '',
            card_no: card_no,
            end_time: 3// 默认3小时后过期
          };
        });
        
        // 构造请求参数
        const addGoodsParams = {
          goods_id: this.goodsId,
          carmines: JSON.stringify(carmines)
        };

        // 打印请求参数
        console.log('=== 添加卡密请求参数 ===');
        console.log('carmines数据:', carmines);
        console.log('完整请求参数:', addGoodsParams);
        console.log('========================');

        // 调用添加卡密接口
        let res;
        if (this.$api?.goods?.addGoods) {
          res = await this.$api.goods.addGoods(addGoodsParams);
        } else {
          const { goodsApi } = await import('@/utils/api');
          res = await goodsApi.addGoods(addGoodsParams);
        }

        uni.hideLoading();

        console.log('=== 添加卡密接口响应 ===');
        console.log('完整响应数据:', res);
        console.log('响应数据结构:', JSON.stringify(res, null, 2));
        console.log('========================');

        if (res?.code === 200 || res?.success) {
          uni.showToast({
            title: '卡密上架成功',
            icon: 'success'
          });
          
          // 清空输入的卡密
          this.accountNumber = '';
          this.accountList = [];
          
          // 可以跳转到卡密管理页面或刷新当前页面
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res?.msg || '卡密上架失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('添加卡密失败:', error);
        uni.showToast({
          title: error?.message || '卡密上架失败',
          icon: 'none'
        });
      }
    },
    
    // 关闭购买弹窗
    closeBuyModal() {
      this.showBuyModal = false;
    },
    
    // 处理支付完成事件
    handlePaymentComplete(paymentData) {
      console.log('支付完成:', paymentData);
      
      // 关闭支付弹窗
      this.showBuyModal = false;
      
      // 显示支付接口返回的msg信息
      let toastTitle = '支付成功';
      if (paymentData.response && paymentData.response.msg) {
        toastTitle = paymentData.response.msg;
      }
      
      uni.showToast({
        title: toastTitle,
        icon: 'success',
        duration: 1500
      });
      
      // 跳转到订单详情页面
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/order/buydetail?orderId=${this.currentOrderId}`
        });
      }, 1500);
    },
    
    // 处理支付
    handlePayment(paymentData) {
      console.log('支付数据:', paymentData)
      
      // 关闭弹窗
      this.showBuyModal = false
      
      // 根据支付方式处理
      switch(paymentData.paymentType) {
        case 'alipay':
          uni.showToast({
            title: '正在跳转支付宝支付...',
            icon: 'none'
          })
          break
        case 'wechat':
          uni.showToast({
            title: '正在跳转微信支付...',
            icon: 'none'
          })
          break
        case 'balance':
          uni.showToast({
            title: '正在使用余额支付...',
            icon: 'none'
          })
          break
      }
      
      // 模拟支付成功后跳转
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/pay/success'
        })
      }, 1500)
    },

    // 加载商品详情
    async fetchGoodsInfo() {
      if (!this.goodsId || this.loading) return;
      this.loading = true;
      try {
        let res;
        if (this.$api?.goods?.getGoodsInfo) {
          res = await this.$api.goods.getGoodsInfo(this.goodsId);
        } else {
          const { goodsApi } = await import('@/utils/api');
          res = await goodsApi.getGoodsInfo(this.goodsId);
        }
        
        if (res?.data) {
          const goodsInfo = res.data;
          this.currentGoodsInfo = {
            title: goodsInfo.goods_name || goodsInfo.title || '',
            price: goodsInfo.price || '0.00',
            stock: goodsInfo.num || goodsInfo.stock || '0',
            image: (goodsInfo.imgs && goodsInfo.imgs.length > 0) ? String(goodsInfo.imgs[0]).replace(/`/g, '') : this.currentGoodsInfo.image,
            desc: goodsInfo.desc || '',
            content: goodsInfo.content || '',
            cost_price: goodsInfo.cost_price || '0.00',
            class_name: goodsInfo.class_name || '',
            unit: goodsInfo.unit || this.currentGoodsInfo.unit || '个',
            specs: goodsInfo.specs || [], // 商品规格数组
            channel_ids: goodsInfo.channel_ids || [], // 支持的平台ID数组
            charge_address: goodsInfo.charge_address || '' // 卡密激活地址
          };
          
          // 如果有规格，默认选择第一个规格
           if (this.currentGoodsInfo.specs && this.currentGoodsInfo.specs.length > 0) {
             this.selectedSpec = this.currentGoodsInfo.specs[0];
             // 更新价格和库存为选中规格的价格和库存
             this.currentGoodsInfo.price = this.selectedSpec.price || this.currentGoodsInfo.price;
             this.currentGoodsInfo.stock = this.selectedSpec.num || this.currentGoodsInfo.stock;
           } else {
             this.selectedSpec = null;
           }
        } else if (res?.code === 0 && res?.msg) {
          uni.showToast({ title: res.msg, icon: 'none' });
        }
      } catch (err) {
        console.error('获取商品详情失败:', err);
        uni.showToast({ title: err?.message || '加载商品详情失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 将后端 content 中可能包含的反引号清理，避免渲染异常
    safeHtml(html) {
      if (!html) return '';
      return String(html).replace(/`/g, '');
    },

    // 关闭价格设置弹窗
    closePriceModal() {
      this.showPriceModal = false;
      this.pendingCarmineList = [];
    },

    // 确认价格并上架卡密
    async confirmPrice(price) {
      this.showPriceModal = false;
      
      if (this.pendingCarmineList.length > 0) {
        await this.addGoodsToMarket(this.pendingCarmineList, price);
      }
      
      this.pendingCarmineList = [];
    },

    // 获取快捷价格选项
    getQuickPrices() {
      const basePrice = parseFloat(this.selectedSpec ? this.selectedSpec.price : this.currentGoodsInfo.price) || 10;
      
      // 基于商品价格生成合理的快捷价格选项
      const prices = [
        (basePrice * 0.8).toFixed(1),  // 8折
        (basePrice * 0.9).toFixed(1),  // 9折
        basePrice.toFixed(1),          // 原价
        (basePrice * 1.1).toFixed(1),  // 1.1倍
        (basePrice * 1.2).toFixed(1)   // 1.2倍
      ];
      
      // 确保价格格式正确，去掉不必要的小数点
      return prices.map(price => {
        const num = parseFloat(price);
        return num % 1 === 0 ? num.toString() : num.toFixed(1);
      });
    }
  }
}
</script>

<style scoped>
.goods-detail-page {
  min-height: 100vh;
  background-color: #F2F2F2;
  padding-bottom: 80px;
}

/* 状态栏占位 */
.status-bar {
  height: var(--status-bar-height, 44px);
  background-color: #ffffff;
}

/* 导航栏 */
.nav-bar {
  height: 44px;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  gap: 12px;
}

.nav-back {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.nav-search-container {
  flex: 1;
  height: 32px;
}

.nav-search-box {
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 16px;
  display: flex;
  align-items: center;
  padding: 0 12px;
  gap: 8px;
}

.nav-more {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.back-icon, .more-icon {
  width: 20px;
  height: 20px;
}

.search-icon {
  width: 16px;
  height: 16px;
  opacity: 0.6;
}

.search-placeholder {
  font-size: 14px;
  color: #999999;
  flex: 1;
}

/* 商品主图和信息左右布局 */
.goods-main-section {
  display: flex;
  padding: 16px;
  background-color: #ffffff;
  gap: 16px;
  border-radius: 12px;
  margin: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 左侧商品图片 */
.goods-image-section {
  width: 5.5rem;
  height: 5.5rem;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
}

.goods-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  background-color: #dedcdc;
}

/* 右侧商品信息 */
.goods-info-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-title-section {
  margin-bottom: 12px;
}

.goods-title {
  font-size: 18px;
  font-weight: 500;
  color: #333333;
  line-height: 1.4;
}

.price-section {
  display: flex;
  align-items: center;
  
}

.price-container {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 16px;
  font-weight: 500;
  color: #ff4757;
}

.price-number {
  font-size: 24px;
  font-weight: 600;
  color: #ff4757;
}

.stock-info {
  font-size: 14px;
  color: #999999;
  margin-left: 0.5rem;
}

/* 商品类型和时长选择 */
.product-type-section,
.product-duration-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 卡密有效期选择 */
.quality-time-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-label {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.time-options {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-top: 10px;
}

.time-option {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.option-circle {
  width: 12px;
  height: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 50%;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.option-circle.checked {
  border-color: #ff4757;
  background-color: #ff4757;
}

.check-mark {
  color: #ffffff;
  font-size: 12px;
  font-weight: bold;
}

.option-label {
  font-size: 14px;
  color: #333333;
  user-select: none;
}

.consignment-type-container {
  margin-top: 16px;
}

.consignment-options {
  display: flex;
  gap: 24px;
}

.consignment-option {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  background-color: #ffffff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.consignment-option.selected {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.consignment-option .option-circle {
  width: 20px;
  height: 20px;
}

.consignment-option .option-label {
  font-size: 14px;
  font-weight: 500;
}

.consignment-option.selected .option-label {
  color: #ff4757;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.option-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 0.8rem;
}

.option-btn {
  padding: 0.45rem 1.2rem;
  border: 2px solid #e0e0e0;
  border-radius: 24px;
  background-color: #ffffff;
  transition: all 0.3s ease;
}

.option-btn.active {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.option-text {
  font-size: 14px;
  color: #666666;
}

.option-btn.active .option-text {
  color: #ff4757;
  font-weight: 500;
}

/* 充值账号填写 */
.account-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 充值账号三列布局容器 */
.account-header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.account-header-container .section-title {
  flex: 1;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  margin: 0;
}

.account-type-options {
  display: flex;
  gap: 24px;
  margin-bottom: 0.5rem;
  margin-top: 0.5rem;
}

.account-type-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.account-type-btn:hover {
  background-color: #f8f9fa;
}

.account-header-container .account-type-btn {
  flex: 0 0 auto;
}

.radio-icon {
  width: 12px;
  height: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 50%;
  background-color: #ffffff;
  position: relative;
  transition: all 0.3s ease;
}

.radio-icon.active {
  border-color: #ff4757;
  background-color: #ff4757;
}

.radio-icon.active::after {
  content: '✓';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ffffff;
  font-size: 12px;
  font-weight: bold;
}

.account-type-text {
  font-size: 14px;
  color: #333333;
}

/* 输入框和添加按钮两列布局容器 */
.account-input-container {
  margin-top: 16px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.account-input {
  width: 100%;
  min-height: 125px;
  max-height: 200px;
  padding: 16px 56px 16px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  background-color: #f8f9fa;
  font-size: 14px;
  color: #333333;
  outline: none;
  transition: all 0.3s ease;
  box-sizing: border-box;
  resize: none;
  line-height: 1.5;
}

.account-input:focus {
  border-color: #ff4757;
  background-color: #ffffff;
}

.account-input::placeholder {
  color: #999999;
}

.add-account-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #999999;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.add-account-btn:hover {
  background-color: #777777;
  transform: scale(1.05);
}

.add-icon {
  font-size: 24px;
  color: #ffffff;
  font-weight: bold;
}

.add-icon-img {
  width: 24px;
  height: 24px;
}

.floating-icon {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 10;
}

.floating-icon:hover {
  transform: translateY(-50%) scale(1.1);
}

/* 多账号列表 */
.account-list {
  margin-top: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.account-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 16px;
  margin-bottom: 8px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 20px;
  transition: all 0.3s ease;
  height: 24px;
}

.account-item:last-child {
  margin-bottom: 0;
}

.account-item:hover {
  background-color: #e9ecef;
}

.account-text {
  flex: 1;
  font-size: 14px;
  color: #333333;
  word-break: break-all;
}

.remove-account-btn {
  width: 24px;
  height: 24px;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 8px;
  transition: all 0.3s ease;
}

.remove-account-btn:hover {
  background-color: #ff3742;
  transform: scale(1.1);
}

.remove-icon {
  font-size: 16px;
  color: #ffffff;
  font-weight: bold;
  line-height: 1;
}

.remove-icon-img {
  width: 24px;
  height: 24px;
}

/* 卡密激活地址 */
.activation-address-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.address-display {
  margin-top: 12px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  border-left: 4px solid #ff4757;
}

.address-text {
  font-size: 14px;
  color: #333333;
  line-height: 1.5;
  word-break: break-all;
}

.warning-notice {
  margin-top: 16px;
  padding: 16px;
  background-color: #fff5f5;
  border: 1px solid #ffebee;
  border-radius: 8px;
  border-left: 4px solid #ff4757;
}

.notice-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.warning-icon {
  width: 20px;
  height: 20px;
}

.notice-title {
  font-size: 16px;
  font-weight: 600;
  color: #ff4757;
}

.notice-content {
  font-size: 13px;
  color: #666666;
  line-height: 1.6;
  text-align: justify;
}

/* 购买数量 */
.quantity-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.quantity-label {
  font-size: 14px;
  color: #333333;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  background-color: #ffffff;
  overflow: hidden;
}

.quantity-btn {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.quantity-btn:hover {
  background-color: #f8f9fa;
}

.quantity-btn-text {
  font-size: 18px;
  color: #666666;
  font-weight: 500;
}

.add-icon {
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-value {
  font-size: 16px;
  color: #333333;
  margin: 0 16px;
  min-width: 24px;
  text-align: center;
  font-weight: 500;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
}

.bottom-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.bottom-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.home-icon, .service-icon {
  width: 24px;
  height: 24px;
}

.bottom-btn-text {
  font-size: 10px;
  color: #666666;
}

.bottom-right {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: 20px;
}

.buy-btn {
  flex: 1;
  height: 40px;
  background-color: #ff4757;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.buy-btn-text {
  font-size: 14px;
  color: #ffffff;
  font-weight: 500;
}

/* 成交记录 */
.transaction-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.transaction-table {
  margin-top: 16px;
  border-radius: 8px;
}

.table-header {
  display: flex;
  background-color: #f5f5f5;
  padding: 12px 0;
  border-radius: 0.4rem;
}

.table-body {
  background-color: #ffffff;
}

.table-row {
  display: flex;
  padding: 0.25rem 0;
  

}

.table-row:last-child {
  border-bottom: none;
}

.even-row {
  background-color: #f9f9f9;
  border-radius: 0.5rem;
}

.header-cell, .body-cell {
  flex: 1;
  text-align: center;
  font-size: 14px;
}

.header-cell {
  color: #666666;
  font-weight: 500;
}

.body-cell {
  color: #333333;
}

.time-cell {
  flex: 1.2;
}

.price-cell {
  flex: 0.8;
}

.duration-cell {
  flex: 1;
}

/* 销售渠道 */
.channel-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.platform-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 16px;
  margin-bottom: 24px;
  justify-content: flex-start;
}

.platform-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.platform-icon {
  width: 1rem;
  height: 1rem;
  flex-shrink: 0;
}

.platform-text {
  font-size: 0.75rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.platform-item.supported .platform-text {
  color: #111111;
}

.platform-item.unsupported .platform-text {
  color: #999999;
}

/* 保障服务板块 */
.guarantee-service-section {
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.guarantee-section {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  border-radius: 8px;
  margin-top: 16px;
}

.guarantee-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.guarantee-icon {
  width: 32px;
  height: 32px;
}

.guarantee-text {
  font-size: 12px;
  color: #666666;
  text-align: center;
}

/* 商品详情板块 */
.product-detail-section {
  padding: 20px 16px;
}

.detail-content {
  margin-top: 16px;
  min-height: 200px;
  border: 2px dashed #e0e0e0;
  border-radius: 8px;
  background-color: #fafafa;
  padding: 8px;
  display: block;
  overflow: hidden;
  word-break: break-word;
}

/* 兜底：针对图片可能带固定尺寸的属性 或 style */
.detail-content :deep(img[width]),
.detail-content :deep(img[height]) {
  width: auto !important;
  height: auto !important;
}

/* 兜底：表格内容滚动且不超出容器 */
.detail-content :deep(table) {
  display: block;
  max-width: 100%;
  overflow-x: auto;
}

/* 使详情内富文本媒体自适应容器（适配 v-html + scoped） */
.detail-content :deep(img),
.detail-content :deep(video),
.detail-content :deep(iframe) {
  max-width: 100% !important;
  height: auto !important;
  display: block;
}

/* 兼容 ::v-deep 语法（不同构建工具写法） */
:deep(.detail-content img),
:deep(.detail-content video),
:deep(.detail-content iframe) {
  max-width: 100% !important;
  height: auto !important;
  display: block;
}

.detail-placeholder {
  text-align: center;
}

.detail-placeholder-text {
  font-size: 14px;
  color: #999999;
  line-height: 1.5;
}
</style>